#!/usr/bin/env node

// 读取命令行参数中的提交消息文件路径
import { readFileSync } from 'fs';

const filePath = process.argv[2];

// 读取提交消息
let commitMessage;
try {
  commitMessage = readFileSync(filePath, 'utf8').trim();
} catch (error) {
  console.error('无法读取提交消息文件:', error);
  process.exit(1);
}

// 定义正则表达式验证提交消息格式
// 格式: <type>(<scope>): <subject>
// 其中type可以是: feat, fix, docs, style, refactor, test, chore, build, ci, perf, revert
const pattern =
  /^(feat|fix|docs|style|refactor|test|chore|build|ci|perf|revert)(\([a-z0-9_-]+\))?: [a-z].{1,72}$/;

// 验证提交消息
if (!pattern.test(commitMessage)) {
  console.error('\x1b[31m提交消息格式不正确!\x1b[0m');
  console.log('\x1b[32m正确格式: <type>(<scope>): <subject>\x1b[0m');
  console.log(
    '\x1b[32m  type: feat, fix, docs, style, refactor, test, chore, build, ci, perf, revert\x1b[0m'
  );
  console.log('\x1b[32m  scope: 可选，描述修改的范围\x1b[0m');
  console.log('\x1b[32m  subject: 简短描述，首字母小写，不超过72个字符\x1b[0m');
  process.exit(1);
} else {
  console.log('\x1b[32m提交消息格式正确!\x1b[0m');
  process.exit(0);
}
